<?php

/**
 * This is the model class for table "tbl_locations".
 *
 * The followings are the available columns in table 'tbl_locations':
 * @property integer $id
 * @property string $custno
 * @property string $locno
 * @property string $locname
 * @property string $locnickname
 * @property string $add1
 * @property string $add2
 * @property string $city
 * @property string $state
 * @property string $zip
 * @property string $notes 
 * @property double $laborrate
 * @property double $helperrate
 * @property string $branch
 * @property double $tripcharge
 * @property integer $taxfrp
 * @property string $salesref
 * @property double $latitude
 * @property double $longitude
 * @property integer $disableemails
 * @property integer $locationinactive
 * @property string $image
 * @property string $timezone
 * @property string $county
 * @property integer $isexempt
 */
class Locations extends CActiveRecord {
    public $file;
    const LOCNO_LENGTH=5;
    public static function getList($custno=null){
        $crit = new CDbCriteria();        
        $crit->compare('custno',$custno);
        $list=Locations::model()->findAll($crit);
        $rs=array(''=>'N/A');
        foreach($list as $item){
            $rs[$item->locno]="$item->locname | $item->add1 | $item->city | $item->state";
        }
        return $rs;
    }
    /**
     * Returns the static model of the specified AR class.
     * @return Locations the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'tbl_locations';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('locname, add1, city, state, disableemails, locationinactive', 'required'),
            array('isexempt,taxfrp, disableemails, locationinactive', 'numerical', 'integerOnly' => true),
            array('county','length','max'=>150),
            array('county','safe'),
            array('latitude, longitude', 'numerical'),
            array('custno', 'length', 'max' => 7, 'min' => 7),
            array('locno', 'length', 'max' => 5, 'min' => 5),
            array('lockby,locktime','length','max'=>20),
            array('locname, locnickname, add1, add2', 'length', 'max' => 50),
            array('city', 'length', 'max' => 30),
            array('state', 'length', 'max' => 15),
            array('zip', 'length', 'max' => 10),
            array('notes', 'length', 'max' => 255),
            array('specialnotes','safe'),
            array('salesref', 'length', 'max' => 15),
            array('file','file','types'=>'jpg,png,jpeg,bmp,gif','maxSize'=>5000000,'allowEmpty'=>true),
            array('timezone','exist','className'=>'Timezone','attributeName'=>'id'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, custno, locno, locname, locnickname, add1, add2, city, state, zip, notes, laborrate, helperrate, branch, tripcharge, taxfrp, salesref, latitude, longitude, disableemails, locationinactive', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'customer'=>array(self::BELONGS_TO,'Customers','custno'),
            
        );
    }
    public function getLocationcontacts(){
        return Locationcontacts::model()->findAll('custno=:custno AND locno=:locno',array(
            'custno'=>$this->custno,
            'locno'=>$this->locno
        ));
    }
    public static function getText($custno,$locno){
        $row=Yii::app()->db
                ->createCommand('select locname,add1,city,state,zip from tbl_locations where custno=:custno and locno=:locno')
                ->bindValues(array(
                    'custno'=>$custno,
                    'locno'=>$locno
                ))
                ->queryRow();
        if($row!==false){
            return $row['locname'].' ,'.$row['add1'].' ,'.$row['city'].' ,'.$row['state'].' ,'.$row['zip'];
        }
        return '';
                
    }
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'custno' => 'Customer number',
            'locno' => 'Location number',
            'locname' => 'Location name',
            'locnickname' => 'Nickname',
            'add1' => 'Address 1',
            'add2' => 'Address 2',
            'city' => 'City',
            'state' => 'State',
            'zip' => 'Zip',
            'notes' => 'Notes',
       
            'laborrate' => 'Laborrate',
            'helperrate' => 'Helperrate',
            'branch' => 'Branch',
            'tripcharge' => 'Tripcharge',
            'taxfrp' => 'Taxfrp',
            'salesref' => 'Salesref',
            'latitude' => 'Latitude',
            'longitude' => 'Longitude',
            'disableemails' => 'Email Statements',
            'locationinactive' => 'Location Status',
            'timezone'=>'Time zone',
            'isexempt'=>'Is Exempt'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('custno', $this->custno, true);
        $criteria->compare('locno', $this->locno, true);
        $criteria->compare('locname', $this->locname, true);
        $criteria->compare('locnickname', $this->locnickname, true);
        $criteria->compare('add1', $this->add1, true);
        $criteria->compare('add2', $this->add2, true);
        $criteria->compare('city', $this->city, true);
        $criteria->compare('state', $this->state, true);
        $criteria->compare('zip', $this->zip, true);
        $criteria->compare('notes', $this->notes, true);
       
        $criteria->compare('laborrate', $this->laborrate);
        $criteria->compare('helperrate', $this->helperrate);
        $criteria->compare('branch', $this->branch, true);
        $criteria->compare('tripcharge', $this->tripcharge);
        $criteria->compare('taxfrp', $this->taxfrp);
        $criteria->compare('salesref', $this->salesref, true);
        $criteria->compare('latitude', $this->latitude);
        $criteria->compare('longitude', $this->longitude);
        $criteria->compare('disableemails', $this->disableemails);
        $criteria->compare('locationinactive', $this->locationinactive);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /*
     * Get array of location contacts
     * @return array
     */


    /*
     * 
     */

  
    public function getLocationNumber(){
        if($this->isNewRecord){
            $num = Yii::app()->db->createCommand('select max(cast(locno as unsigned)) from tbl_locations where custno=:custno')->queryScalar(array(
                'custno'=>$this->custno,
            ));
            $this->locno = str_pad($num + 1, self::LOCNO_LENGTH, '0', STR_PAD_LEFT);
        }else{
            return $this->locno;
        }
    }
    public function beforeSave() {
        
        
        $this->file=CUploadedFile::getInstance($this, 'file');
        if($this->file!=NULL){
                //made a random name base on timestamp
            $ext=getFileExt($this->file);
            $name=getFileBodyName($this->file);

            
            $this->image=$name.'_'.time().$ext;
         
            $this->file->saveAs('images/content/'.$this->image,true);   
        }
        
        return parent::beforeSave();
      
        
    }
    
    public function getTimeZoneList(){
        $data=Yii::app()->db->createCommand('select * from tbl_timezone')->queryAll();
        $rs=array();
        if(count($data)>0){
            foreach($data as $item){
                $rs[$item['id']]=$item['id'];
            }
        }
        return $rs;
    }
  
    public function getActiveText(){
        return isset($this->locationInactiveList[$this->locationinactive])?$this->locationInactiveList[$this->locationinactive]:NULL;
    }
    public function getLocationInactiveList(){
        return array(
            '-1'=>'Pending',
            '0'=>'Active',
            '1'=>'Inactive',
        );
    }
    const TAX_EXEMPT_YES=-1;
    const TAX_EXEMPT_NO=0;
    public function getIsExemptList(){
        return array(
            self::TAX_EXEMPT_NO=>'No',
            self::TAX_EXEMPT_YES=>'Yes'
        );
    }
    public function getIsExemptYes(){
        return isset($this->isExemptList[$this->isexempt])?$this->isExemptList[$this->isexempt]:NULL;
    }
    public function getStateList(){
        return array(
            'AL'=>'AL',
            'AK'=>'AK',
            'AZ'=>'AZ',
            'AR'=>'AR',
            'CA'=>'CA',
            'CO'=>'CO',
            'CT'=>'CT',
            'DE'=>'DE',
            'FL'=>'FL',
            'GA'=>'GA',
            'HI'=>'HI',
            'ID'=>'ID',
            'IL'=>'IL',
            'IN'=>'IN',
            'IA'=>'IA',
            'KS'=>'KS',
            'KY'=>'KY',
            'LA'=>'LA',
            'ME'=>'ME',
            'MD'=>'MD',
            'MA'=>'MA',
            'MI'=>'MI',
            'MN'=>'MN',
            'MS'=>'MS',
            'MO'=>'MO',
            'MT'=>'MT',
            'NE'=>'NE',
            'NV'=>'NV',
            'NH'=>'NG',
            'NJ'=>'NJ',
            'NM'=>'NM',
            'NY'=>'NY',
            'NC'=>'NC',
            'ND'=>'ND',
            'OH'=>'OH',
            'OK'=>'OK',
            'OR'=>'OR',
            'PA'=>'PA',
            'PR'=>'PR',
            'RI'=>'RI',
            'SC'=>'SC',
            'SD'=>'SD',
            'TN'=>'TN',
            'TX'=>'TX',
            'UT'=>'UT',
            'VT'=>'VT',
            'VA'=>'VA',
            'WA'=>'WA',
            'WV'=>'WV',
            'WI'=>'WI',
            'WY'=>'WY',
        );
    }
    public function getTotalPaidPayment(){
        $paid=Yii::app()->db->createCommand('select sum(paid) from tbl_rec where custno=:custno AND locno=:locno')->bindValues(array(
            'custno'=>$this->custno,
            'locno'=>$this->locno,
        ))->queryScalar();
        if($paid!==false && $paid!=NULL){
            return number_format($paid,2);
        }
        return 0;
    }
    public function getTotalUnpaidPayment(){
        $money=Yii::app()->db->createCommand('select sum(invamt - paid) from tbl_rec where custno=:custno AND locno=:locno')->bindValues(array(
            'custno'=>$this->custno,
            'locno'=>$this->locno,
        ))->queryScalar();
        if($money!==false && $money!=NULL){
            return number_format($money,2);
        }
        return 0;
    }
    public function getTotalUninvoicedWork(){
        $salesOrderList=Invoice::model()->findAll('invoicetype=:type AND custno=:custno AND locno=:locno',array(
            'type'=>Invoice::TYPE_SALES_ORDERS,
            'custno'=>$this->custno,
            'locno'=>$this->locno
        ));
        $rs=0;
        /* @var $salesOrder Invoice */
        foreach($salesOrderList as $salesOrder){
            $invoice=Yii::app()->db->createCommand('select invoice from tbl_invoice where salesordersorg=:salesOrder')->bindValue('salesOrder', $salesOrder->invoice)->queryScalar();
            //if there is no invoice associate with this sales order yet
            if($invoice===false || $invoice==NULL){
                $rs+=$salesOrder->amountcharge;
            }
        }
        return number_format($rs,2);
    }
    
    
}
